package drds.plus.executor.row_values.row_value;

import drds.plus.executor.cursor.cursor_metadata.CursorMetaData;
import drds.plus.executor.row_values.RowValues;
import drds.plus.sql_process.abstract_syntax_tree.expression.item.Item;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 根据给定的字段遍历, ps. 期望的字段列表不一定是cursor meta中的返回顺序，需要做index映射
 */
public class RowValueScanerImpl implements IRowValueScaner {

    private final CursorMetaData cursorMetaData;
    private final List<Item> itemList;
    private final List<Integer> indexList;

    /**
     * @param cursorMetaData
     * @param itemList       itemList中列相同,但是在cursorMetaData的顺序不一致。所以通过内部的indexList进行统一,在值遍历的时候Integer rowDataIndex = indexList.get(columnIndex);会取到同一个；列
     */
    public RowValueScanerImpl(CursorMetaData cursorMetaData, List<Item> itemList) {
        super();
        this.cursorMetaData = cursorMetaData;
        this.itemList = itemList;
        indexList = new ArrayList<Integer>(itemList.size());
        for (Item item : itemList) {
            Integer index = this.cursorMetaData.getIndex(item.getTableName(), item.getColumnName(), item.getAlias());
            indexList.add(index);
        }
    }

    public Iterator<Object> rowDataValueIterator(RowValues rowData) {
        return new RowValueIteratorImpl(indexList, rowData);
    }

}
